<?php

class AclPlugin extends Zend_Controller_Plugin_Abstract{
    private $_authEngine;
    private $_acl;
    
    public function __construct($auth,Zend_Acl $acl){
        $this->_acl         = $acl;
        $this->_authEngine  = $auth;
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request){
        $resource 	= $request->getActionName();
        $privilage 	= $request->getControllerName();
        //$module		= $this->getModuloPath($request->getModuleName());
        $module		= $request->getModuleName();

        $privilage	= $module . ':' . $privilage;
        $storageObj     = $this->_authEngine->getStorage()->read();
        
        
        //verifica se esta autenticado
        if( $this->_authEngine->hasIdentity()){
            $role = $storageObj['id'];
        }else{
            Zend_Auth::getInstance()->clearIdentity();
            $role['perfil'] = 'guest';
        }
        
        try {
            $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('Redirector');
            if (!$this->_acl->has($privilage)) {
                  $redirector->gotoUrlAndExit('/index/erro');
            }
            
            if(!$this->_acl->isAllowed($role['perfil'],$privilage)&& $role['perfil'] != 'guest' ) {
                $redirector->gotoUrlAndExit('/dashboard/dashboard');
            }else if(!$this->_acl->isAllowed($role['perfil'],$privilage)&& $role['perfil'] == 'guest'){
                $redirector->gotoUrlAndExit('/index/erro');
            }
        }catch (Zend_Exception $e) {
            echo '';//$e->getMessage();
        }catch(Zend_Acl_Exception $e) {
            //echo $e->getMessage();
        }
    }
    
    private function getModuloPath($name){
        $sessioModulos = new Zend_Session_Namespace('modulos');
        
        if(!isset($sessioModulos->modulos)){
            $sessioModulos->modulos = Application_Model_Modulo::getInstance()->getModulos();
        }
        
        $retorno= $name;
        
        foreach ($sessioModulos->modulos as $modulo) {
            if($name == $modulo['chave'] && is_null($modulo['labelPasta'])){
                $retorno = $name;
                break;
            }else if($name == $modulo['chave'] && !is_null($modulo['labelPasta'])){
                $retorno = $modulo['labelPasta'];
                break;
            }
        }
        
        return $retorno;
    }
}
?>